<script lang="ts" setup>
import type { GroupVO } from '#/api/register/group/model';

import { onMounted, ref, watch } from 'vue';

import { Select, Spin } from 'ant-design-vue';
import { debounce } from 'lodash-es';

import { groupInfo, groupList } from '#/api/register/group';

interface Props {
  exhibitionId?: number | string;
}

const props = withDefaults(defineProps<Props>(), {
  exhibitionId: undefined,
});

const emit = defineEmits(['blur', 'change', 'select']);
const loading = ref(false);
// const isLoaded = ref(false);
const notFoundContent = ref<any>(null);
const currGroupName = ref('');
const list = ref<GroupVO[]>([]);
const modelValue = defineModel<number | string>('value', {
  default: () => undefined,
});

let isFirstLoad = true;
watch(
  () => modelValue.value,
  async (newVal) => {
    if (newVal && isFirstLoad) {
      // 仅编辑场景时首次触发，防止手动选择时重复查询
      isFirstLoad = false;
      const group = await groupInfo(newVal);
      if (group) {
        list.value = [{ value: group.id, label: group.name }];
      }
    }
  },
  { immediate: true },
);

onMounted(async () => {
  //
});

const getList = debounce(async (name: string) => {
  currGroupName.value = name;
  if (!name) return;
  list.value = [];
  loading.value = true;

  const results =
    (await groupList({ name, exhibitionId: props.exhibitionId })) ?? [];
  if (currGroupName.value === name) {
    list.value = results.map((item) => {
      return { label: item.name, value: item.id };
    });
    notFoundContent.value = results?.length > 0 ? null : '没有查到参观团';
  }
  loading.value = false;
}, 300);

async function handleSearch(val: string) {
  if (!val) return;
  await getList(val);
}

async function handleChange(val: string) {
  console.log(val);
  currGroupName.value = val;
  emit('change', modelValue.value);
}

async function handleSelect(val: string) {
  emit('select', val);
}
</script>
<template>
  <Select
    v-model:value="modelValue"
    class="w-full"
    placeholder="搜索参观团并选择"
    show-search
    :show-arrow="false"
    :filter-option="false"
    :default-active-first-option="false"
    :not-found-content="loading ? undefined : notFoundContent"
    :options="list"
    :label-in-value="false"
    @blur="emit('blur')"
    @change="handleChange"
    @search="handleSearch"
    @select="handleSelect"
  >
    <template v-if="loading" #notFoundContent>
      <Spin size="small" />
    </template>
  </Select>
</template>
